package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.WmMaterialDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmTreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Resource
    private FileStorageService fileStorageService;

    @Resource
    private WmMaterialMapper wmMaterialMapper;

    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 上传图片到minio
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1.检查参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2.上传图片到minIO中
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;

        try {
            fileId = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            log.info("上传图片到Minio中，fileId:{}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件上传失败");
        }

        // 3.保存到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(WmTreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(WmTreadLocalUtil.getUser().getId());
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        // 4.返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 获取文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        // 1. 检查参数
        dto.checkParam();

        // 2.分页查询

        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 是否收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }

        // 按照用户查询
        lambdaQueryWrapper.eq(WmMaterial::getUserId, WmTreadLocalUtil.getUser().getId());

        // 按照时间倒叙
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        // 3. 结果返回
        page = page(page, lambdaQueryWrapper);

        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }


    /**
     * 删除照片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(String id) {
        // 1.检查参数
        if (id == null || id.isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 查询数据库
        WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
        if (wmMaterial != null) {
            List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(Wrappers.
                    <WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, wmMaterial.getId()));
            // 是否被文章引用
            if(!wmNewsMaterials.isEmpty() && wmNewsMaterials.size() > 0){
                return ResponseResult.errorResult(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL,"该素材被引用");
            }

            wmMaterialMapper.deleteById(wmMaterial);

            // 删除minIo中的文件
            String url = wmMaterial.getUrl();
            if(url == null || url.isEmpty()){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            fileStorageService.delete(url);
            return ResponseResult.okResult("删除成功");
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
    }

    /**
     * 添加收藏照片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollect(String id,Boolean cancel) {
        // 1.检查参数
        if (id == null || id.isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 查询数据库
        WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
        if (wmMaterial != null) {
            if(cancel) {
                wmMaterial.setIsCollection((short) 1);
            } else {
                wmMaterial.setIsCollection((short) 0);
            }
            wmMaterialMapper.updateById(wmMaterial);
            return ResponseResult.okResult(wmMaterial);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
}
